use core::fmt;

use crate::TextList;

type TListItem<'input> = Box<Vec<ListItem<'input>>>;
#[derive(Debug)]
pub struct ListItem<'input> {
    pub indent: usize,
    pub content: TextList<'input>,
    pub children: Option<TListItem<'input>>,
}
impl<'input> fmt::Display for ListItem<'input> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "<li indent=\"{}\">{}", self.indent, self.content)?;
        if let Some(children) = &self.children {
            write!(f, "<ol>")?;
            for ele in children.iter() {
                write!(f, "<li>{ele}</li>")?;
            }
            write!(f, "</ol>")?;
        }
        write!(f, "</li>")?;
        Ok(())
    }
}
impl<'input> ListItem<'input> {
    pub fn new(indent: usize, content: TextList<'input>) -> Self {
        ListItem {
            indent,
            content,
            children: None,
        }
    }
    pub fn append_item(&mut self, item: ListItem<'input>) {
        if let Some(children) = &mut self.children {
            append_item(children, item)
        } else {
            let children = vec![item];
            self.children = Some(Box::new(children));
        }
    }
}
pub fn generate_list(item: ListItem<'_>) -> Vec<ListItem<'_>> {
    vec![item]
}
pub fn append_item<'input>(list: &mut Vec<ListItem<'input>>, item: ListItem<'input>) {
    let last = list.last_mut().expect("子项此时不能为空");
    if last.indent >= item.indent {
        list.push(item);
    } else {
        last.append_item(item);
    }
}
